﻿using UnityEngine;
using System.Collections;

public class SceneManager : MonoBehaviour 
{
	public TankMovement m_tank;
	public Camera m_mainCamera;
	public CSVReader m_csvReader;
	public Enemy m_enemy;
	public FuelBarrel m_fuelBarrel;
	public TileGenerator m_tileGenerator;
	public GameObject m_explosion;
	public int m_tileWidth = 64;
	public int m_tileHeight = 64;

	public GUITexture m_levelCompleteTexture;
	public GUITexture m_gameOverTexture;
	public int m_playerWinScore = 3;
	public int m_enemyWinScore = 10;

	// Use this for initialization
	void Start () 
	{
		Reset();
	}

	void Reset()
	{
		//m_csvReader.Parse();
		m_tileGenerator.Initialize();
		Vector3 pos = new Vector3(0.0f, 0.0f, 0.0f);
		
		m_tank.SetPosition(new Vector3( m_tileGenerator.m_playerPosX, m_tileGenerator.m_playerPosY, 0.0f) );
		m_tank.m_isAlive = true;
		m_tank.m_isBlocked = false;
		m_enemy.SetPosition(pos);
	}

	// Update is called once per frame
	void Update () 
	{
		if( SceneInformation.GetInstance().m_enemyScore == m_enemyWinScore )
		{
			Debug.Log("Enemy Wins");
			SceneInformation.GetInstance().m_enemyScore = 0;
			SceneInformation.GetInstance().m_playerScore = 0;
			m_gameOverTexture.gameObject.SetActive(true);
			m_tank.SetAlive(false);
			m_enemy.SetAlive(false);
			StartCoroutine(WaitAndLoad(3));
		}
		if( SceneInformation.GetInstance().m_playerScore == m_playerWinScore )
		{
			Debug.Log("Player Wins");
			SceneInformation.GetInstance().m_playerScore = 0;
			SceneInformation.GetInstance().m_enemyScore = 0;
			m_levelCompleteTexture.gameObject.SetActive(true);
			m_tank.SetAlive(false);
			m_enemy.SetAlive(false);
			SceneInformation.GetInstance().m_level += 1;
			StartCoroutine(WaitAndLoad(3));

		}
	}
	
	IEnumerator WaitAndLoad(float t)
	{
		yield return new WaitForSeconds(t);    
		m_levelCompleteTexture.gameObject.SetActive(false);
		Reset();
		m_tank.SetAlive(true);
		m_enemy.SetAlive(true);
	}
	
	IEnumerator WaitAndClose(float t)
	{
		yield return new WaitForSeconds(t);    
		m_gameOverTexture.gameObject.SetActive(true);
	}

	public void ExplodeBarrel( Vector3 explosionPoint )
	{
		Instantiate(m_explosion, explosionPoint, Quaternion.identity);
		m_fuelBarrel.Respawn ();
	}

	public void RespawnFuelBarrel()
	{
		m_fuelBarrel.Respawn ();
	}
}
